package com.hp.es.config;

import lombok.extern.slf4j.Slf4j;
import org.smartboot.license.client.License;
import org.smartboot.license.client.LicenseEntity;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Configuration;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author zhaohp
 * @Title: LicenseConfig
 * @ProjectName hpBoot-es
 * @date 2020/5/2515:05
 * @Description:
 */

@Slf4j
@Configuration
public class LicenseConfig implements InitializingBean, ApplicationContextAware {

    private ApplicationContext context;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        context = applicationContext;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        File file = new File("license.txt");
        License license = new License();
        LicenseEntity licenseEntity = license.loadLicense(file);
        log.info("\n授权时间：{}\n过期时间：{}\n授权码：{}",
                timedate(licenseEntity.getApplyTime()),
                timedate(licenseEntity.getExpireTime()),
                new String(licenseEntity.getData()));
        if (System.currentTimeMillis() >= licenseEntity.getExpireTime()) {
            ConfigurableApplicationContext ctx = (ConfigurableApplicationContext) context;
            ctx.close();

            log.info("-----------------------------------------------------------------");
            log.info("license过期，请联系管理员");
            log.info("-----------------------------------------------------------------");
        }
    }

    public static String timedate(Long time) {
        SimpleDateFormat sdr = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        @SuppressWarnings("unused")
        String times = sdr.format(new Date(time));
        return times;

    }
}
